iT邦幫忙

2022 iThome 鐵人賽

DAY 24
0
Mobile Development

在 Flutter 開發旅程的手札系列 第 24

Flutter Package - Bloc(四)

  • 分享至 

  • xImage
  •  

今天最後要來講如何管理Bloc的State,在Flutter Package - Bloc(三)時,當同樣狀態是Faliure,也有相同的變數reason卻不能寫成下方語法

    if (state is CounterManagementDecreasedFailure||state is CounterManagementIncreasedFailure) {
              await showDialog<String>(
                context: context,
                builder: (BuildContext context) {
                  return AlertDialog(content: Text(state.reason));
                },
              );
            }

這是因為對Bloc而言,他不會因為state內的變數名稱是一樣的,就覺得他們是能互相通用的,因此我們要在Bloc內運用抽象類別,定義CounterManagementFailure來解決這一個問題

在counter_management_bloc.dart內
宣告抽象類別CounterManagementFailure來繼承CounterManagementState,並在Function內放入Failure相同有的變數,讓State能夠拿到

abstract class CounterManagementFailure extends CounterManagementState {
  String reason;
  CounterManagementFailure({required this.reason, required int count}) : super(count: count);
}

製作好後再將狀態是Failure改繼承CounterManagementFailure,並刪除原本寫的Failure
https://ithelp.ithome.com.tw/upload/images/20221009/20152683xxZQWeRKUi.png

在bloc_screen.dart
將原本的listener改為下方語法

listener: (context, state) async {
            if (state is CounterManagementFailure) {
              await showDialog<String>(
                context: context,
                builder: (BuildContext context) {
                  return AlertDialog(content: Text(state.reason));
                },
              );
            }

https://ithelp.ithome.com.tw/upload/images/20221009/20152683lZubGCQU3M.png


完整語法
counter_management_bloc.dart

import 'package:flutter_bloc/flutter_bloc.dart';

class CounterManagementBloc extends Bloc<CounterManagementEvent, CounterManagementState> {
  CounterManagementBloc() : super(CounterManagementInitial()) {
    //當新增事件發生時做的事
    on<CounterManagementIncreased>((event, emit) async {
      if (state.count + 1 <= 10) {
        state.count += 1;
        emit(CounterManagementIncreasedSuccess(count: state.count));
      } else {
        emit(CounterManagementIncreasedFailure(count: state.count, reason: "數值最大10"));
      }
    });
    //當減少事件發生時做的事
    on<CounterManagementDecreased>((event, emit) async {
      if (state.count - 1 >= 0) {
        state.count -= 1;
        emit(CounterManagementDecreasedSuccess(count: state.count));
      } else {
        emit(CounterManagementDecreasedFailure(count: state.count, reason: "數值最小0"));
      }
    });
    //當重置事件發生時做的事
    on<CounterManagementReset>((event, emit) async {
      emit(CounterManagementResetSuccess(count: 0));
    });
  }
}

//EVENT:事件都是發生了才進到Bloc,所以最後面的動作要放上過去分詞
abstract class CounterManagementEvent {}

class CounterManagementIncreased extends CounterManagementEvent {
  CounterManagementIncreased();
}

class CounterManagementDecreased extends CounterManagementEvent {
  CounterManagementDecreased();
}

class CounterManagementReset extends CounterManagementEvent {
  CounterManagementReset();
}

//STATES
//定義state的內容
abstract class CounterManagementState {
  int count;
  CounterManagementState({required this.count});
}

abstract class CounterManagementFailure extends CounterManagementState {
  String reason;
  CounterManagementFailure({required this.reason, required int count}) : super(count: count);
}

//初始狀況
class CounterManagementInitial extends CounterManagementState {
  CounterManagementInitial() : super(count: 0);
}

//定義Event的狀態
class CounterManagementIncreasedSuccess extends CounterManagementState {
  CounterManagementIncreasedSuccess({required int count}) : super(count: count);
}

//當失敗時顯示reason
class CounterManagementIncreasedFailure extends CounterManagementFailure {
  CounterManagementIncreasedFailure({required int count, required String reason}) : super(count: count, reason: reason);
}

class CounterManagementDecreasedSuccess extends CounterManagementState {
  CounterManagementDecreasedSuccess({required int count}) : super(count: count);
}

class CounterManagementDecreasedFailure extends CounterManagementFailure {
  CounterManagementDecreasedFailure({required int count, required String reason}) : super(count: count, reason: reason);
}

//Reset的狀態只會有成功所以不用寫Failure的狀態
class CounterManagementResetSuccess extends CounterManagementState {
  CounterManagementResetSuccess({required int count}) : super(count: count);
}

bloc_screen.dart

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import 'counter_management_bloc.dart';

class BlocScreen extends StatelessWidget {
  const BlocScreen({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: const Text('Counter')),
        body: BlocProvider(
          create: (_) => CounterManagementBloc(),
          child: BlocConsumer<CounterManagementBloc, CounterManagementState>(listener: (context, state) async {
            if (state is CounterManagementFailure) {
              await showDialog<String>(
                context: context,
                builder: (BuildContext context) {
                  return AlertDialog(content: Text(state.reason));
                },
              );
            }
          }, builder: (context, state) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      ElevatedButton(
                        onPressed: () {
                          context.read<CounterManagementBloc>().add(CounterManagementDecreased());
                        },
                        child: const Icon(Icons.remove),
                      ),
                      Text(state.count.toString()),
                      ElevatedButton(
                        onPressed: () {
                          context.read<CounterManagementBloc>().add(CounterManagementIncreased());
                        },
                        child: const Icon(Icons.add),
                      ),
                    ],
                  ),
                  const SizedBox(
                    height: 20,
                  ),
                  ElevatedButton(
                    onPressed: () {
                      context.read<CounterManagementBloc>().add(CounterManagementReset());
                    },
                    child: const Text("reset"),
                  ),
                  const SizedBox(
                    height: 100,
                  ),
                ],
              ),
            );
          }),
        ));
  }
}


上一篇
Flutter Package - Bloc(三)
下一篇
Flutter Package — 用Agora製作視訊功能(一)
系列文
在 Flutter 開發旅程的手札30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言